import os
import shutil
import subprocess

user_back = r'yingsi-user-api'
user_front = r'yingsi-user-web'
admin_back = r'yingsi-admin-api'
admin_front = r'yingsi-admin-web'


# git pull to update the code base
def git_pull(a):
    try:
        ppath = os.path.abspath(f'../{a}')
        subprocess.check_call(['git', 'pull'], cwd=ppath)
        print(f"Repository in '{ppath}' updated successfully.")
    except subprocess.CalledProcessError:
        print(f"Error updating repository in '{ppath}'.")


# use npm install and npm run build to build the front end

def build_front(path):
    ppath = os.path.abspath(f'../{path}')
    print(f'building front-end:{ppath}')
    try:
        subprocess.check_call(['npm', 'install'], cwd=ppath)
        subprocess.check_call(['npm', 'run', 'build'], cwd=ppath)
    except subprocess.CalledProcessError as e:
        print(f"Error building front-end in '{ppath}': {e}")


# use go mod tidy and go build to build the back end
def build_back(path):
    ppath = os.path.abspath(f'../{path}')
    print(f'building back-end:{ppath}')
    try:
        subprocess.check_call(['go', 'mod', 'tidy'], cwd=ppath)
        subprocess.check_call(['go', 'build'], cwd=ppath)
    except subprocess.CalledProcessError as e:
        print(f"Error building back-end in '{ppath}': {e}")


# create app-admin and app-user folders if not already exist for app building
def create_folders():
    print('creating folders')
    base_path = os.path.abspath('..')

    app_admin_path = os.path.join(base_path, 'app-admin')
    app_user_path = os.path.join(base_path, 'app-user')

    # Create the directories if they don't exist
    os.makedirs(app_admin_path, exist_ok=True)
    os.makedirs(app_user_path, exist_ok=True)


# move binary and config.yml to app-admin and app-user folders
def move_files():
    file_mappings = [
        ("../yingsi-admin-api/yingsi-admin-api", "../app-admin/yingsi-admin-api"),
        # ("../yingsi-admin-api/config.yml", "../app-admin/config.yml"),
        ("../yingsi-admin-web/dist", "../app-admin/ui/dist"),
        ("../yingsi-user-api/yingsi-user-api", "../app-user/yingsi-user-api"),
        # ("../yingsi-user-api/config.yml", "../app-user/config.yml"),
        ("../yingsi-user-web/dist", "../app-user/ui/dist"),
    ]

    # Get the absolute path of the script's directory
    script_dir = os.path.dirname(os.path.abspath(__file__))

    # Copy files using the mappings
    for src, dest in file_mappings:
        abs_src = os.path.abspath(os.path.join(script_dir, src))
        abs_dest = os.path.abspath(os.path.join(script_dir, dest))

        # remove first
        if os.path.exists(abs_dest):
            if os.path.isfile(abs_dest):
                os.remove(abs_dest)
            elif os.path.isdir(abs_dest):
                shutil.rmtree(abs_dest)
            print(f'removing files {abs_dest}')

        if os.path.isfile(abs_src):
            shutil.copy(abs_src, abs_dest)
        elif os.path.isdir(abs_src):
            shutil.copytree(abs_src, abs_dest)
    print('moving files')


if __name__ == '__main__':
    create_folders()
    git_pull(user_back)
    git_pull(user_front)
    git_pull(admin_back)
    git_pull(admin_front)
    build_front(user_front)
    build_front(admin_front)
    build_back(user_back)
    build_back(admin_back)
    move_files()
    print('done')
